﻿(function($) {
    $.widget("ui.rioRuler", {
        options : {},

        _create : function() {
            var $self = this;
            var element = $self.element;
            element.addClass('rio-ruler');
            var bar = $self.bar = $('<div class="ruler-bar" style="width: 35px;"></div>').appendTo(element);
            var block = $self.block = $('<div class="ruler-block" style="left: 45px; top: 6px;"></div>').appendTo(element);
            var txt = $self.txt = $('<div class="ruler-txt" style="left:9px;"><span>140cm</span><em></em></div>').appendTo(element);
            
            block.draggable({
                axis:'x',
                drag: function( event, ui ) {
                    if(ui.position.left <= 10){
                        ui.position.left = 10;
                        $self.options.stature = 138;
                    } else if (ui.position.left > 10 && ui.position.left < 45){
                        $self.element.find('.ruler-txt span').html('小于140');
                        $self.options.stature = 138;
                    } else if (ui.position.left >= 45 && ui.position.left <= 395) {
                        var val = parseInt(140 + (ui.position.left - 45) / 5);
                        $self.element.find('.ruler-txt span').html(val + 'cm');
                        $self.options.stature = val;
                    } else if (ui.position.left >= 395 && ui.position.left < 430) {
                        $self.element.find('.ruler-txt span').html('大于210');
                        $self.options.stature = 212;
                    } else if (ui.position.left >= 430){
                        ui.position.left = 430;
                        $self.options.stature = 212;
                    }
                    $self.txt.css('left', ui.position.left - 30);
                    $self.bar.width(ui.position.left - 10);
                },
                start: function( event, ui ) {},
                stop: function( event, ui ) {
                }
            });
            // 设置options
            $self._setOptions($self.options);
        },
        _setOption : function(key, value) {
            var $self = this;
            var left = (value - 140) * 5 + 45;
            switch (key) {
            case 'stature':
                if(value < 140){
                    $self.element.find('.ruler-txt span').html('小于140');
                } else if(value >= 140 && value <= 210){
                    $self.element.find('.ruler-txt span').html(value+ 'cm');
                } else {
                    $self.element.find('.ruler-txt span').html('大于210');
                }
                $self.block.css('left', left);
                $self.txt.css('left', left - 30);
                $self.bar.width(left - 10);
                break;
            default:
                break;
            }
            return this;
        }
    });

})(jQuery);
